/*
 * Copyright 2014 Cungmua, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cungmua.vn.kiosk.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import cungmua.vn.kiosk.AbstractActivity;
import cungmua.vn.kiosk.R;
import cungmua.vn.kiosk.adapter.DonHangAdapter;
import cungmua.vn.kiosk.compone.LoadMoreListView;
import cungmua.vn.kiosk.compone.PullToRefreshBase.OnRefreshListener;
import cungmua.vn.kiosk.compone.PullToRefreshView;
import cungmua.vn.kiosk.db.DatabaseHandler;
import cungmua.vn.kiosk.handle.DonHangHandler;
import cungmua.vn.kiosk.handle.ServiceHandler;
import cungmua.vn.kiosk.model.DonHang;
import cungmua.vn.kiosk.model.NhanVien;
import cungmua.vn.kiosk.model.SKU;
import cungmua.vn.kiosk.network.CallServices;
import cungmua.vn.kiosk.tabs.BadgeTabManager;
import cungmua.vn.kiosk.tabs.TabGroupActivity;
import cungmua.vn.kiosk.utils.ConvertUnsigned;
import cungmua.vn.kiosk.utils.WriteLog;

/**
 * @author kelvin.nguyen
 * 
 */
public class DangGiaoActivity extends AbstractActivity {
	private DonHangAdapter mAdapter;
	private List<DonHang> donhangs = new ArrayList<DonHang>();
	private List<DonHang> donhangsSearch = new ArrayList<DonHang>();
	private PullToRefreshView list_donhang;
	private ProgressDialog dialog;
	private NhanVien nhanvien;
	private DatabaseHandler db;
	ListView actualListView;
	private EditText txt_search;
	private Runnable updateTask;
	private Handler guiThread;
private ConvertUnsigned convertString;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_danggiao);
		// define resource xml
		initView();
		
		convertString=new ConvertUnsigned();
		
		// define database
		db = new DatabaseHandler(self);

		if (db.getAllNhanviens().size() > 0) {
			nhanvien = db.getAllNhanviens().get(0);

			if (nhanvien != null) {
				donhangs = db.getAllDonHangDangGiao();
				if (donhangs.size() < 1) {
					if (isNetworkAvailable()) {
						new getDonHang().execute();
					} else {
						showToast(
								getResources().getString(
										R.string.network_unable),
								Toast.LENGTH_LONG);
						return;
					}
				} else {
					// set badge for tabs
					// int index = donhangs.size();
					// BadgeTabManager.getInstance().setBadgeAtIndex(index, 0);

					mAdapter = new DonHangAdapter(self, donhangs);
					actualListView.setAdapter(mAdapter);
				}
			}
		}

		// Set a listener to be invoked when the list should be refreshed.
		list_donhang.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				list_donhang.setLastUpdatedLabel(DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL));

				// Do work to refresh the list here.
				new getDonHang().execute();
			}
		});

		innitThread();
		txt_search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				queueUpdate(500);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

	}

	private void innitThread() {
		guiThread = new Handler();
		updateTask = new Runnable() {

			@Override
			public void run() {
				String keyword = txt_search.getText().toString().trim();

				if (keyword.length() < 1) {
					mAdapter = new DonHangAdapter(self, donhangs);
					actualListView.setAdapter(mAdapter);
				} else {
					donhangsSearch = new ArrayList<DonHang>();
					// get data from keyword fillter
						donhangsSearch=getDataByKeyword(keyword);
					mAdapter = new DonHangAdapter(self, donhangsSearch);
					actualListView.setAdapter(mAdapter);
				}
				// process search with keyword here
				//new getFillterDonHang(keyword).execute();
			}
		};
	}
	
	public List<DonHang> getDataByKeyword(String keyword){
		donhangsSearch=new ArrayList<DonHang>();
		keyword=keyword.toLowerCase();
		for (int i = 0; i < donhangs.size(); i++) {
			String containname=donhangs.get(i).getAddress().toLowerCase();
			if((convertString.ConvertString(containname).contains(convertString.ConvertString(keyword)))){
				donhangsSearch.add(donhangs.get(i));
			}
		}
		
		
		return donhangsSearch;
	}

	private void queueUpdate(long delayMillisecond) {
		guiThread.removeCallbacks(updateTask);
		guiThread.postDelayed(updateTask, delayMillisecond);

	}

	public void initView() {
		txt_search = (EditText) findViewById(R.id.txt_search);
		list_donhang = (PullToRefreshView) findViewById(R.id.list_donhang);
		actualListView = list_donhang.getRefreshableView();

		actualListView.setOnItemClickListener(onItemClick);
	}

	public class getFillterDonHang extends AsyncTask<Void, Void, List<DonHang>> {

		private String keyword;

		public getFillterDonHang(String keyword) {
			this.keyword = keyword;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected List<DonHang> doInBackground(Void... params) {
			String key_search = keyword.length() < 1 ? "%" : keyword;

			List<DonHang> search_donhangs = new ArrayList<DonHang>();

			return search_donhangs = db.getDonHangByKeyword(key_search);

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(List<DonHang> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {
				mAdapter = new DonHangAdapter(self, result);
				actualListView.setAdapter(mAdapter);
			}
		}

	}

	public class getDonHang extends AsyncTask<Void, Void, Integer> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(getParent());
			dialog.setMessage(getResources().getString(R.string.label_dialog));
			dialog.show();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			String json = CallServices.getDonHangs(self,
					String.valueOf(nhanvien.getId()), 1, nhanvien.getToken());
			ServiceHandler service = new ServiceHandler();
			DonHangHandler donhangHandler = null ;
			if(json!=null){
				WriteLog.d(TAG, json);

				 donhangHandler = service.getDonHangs(json);
				 donhangs = donhangHandler.getData();

			}
			// int index = donhangs.size();
			// BadgeTabManager.getInstance().setBadgeAtIndex(index, 0);

			return donhangHandler.getCode();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			switch (result) {
			case 0:
				for (DonHang dh : donhangs) {
					DonHang donhang = db.getDonHang(dh.getOrderId());
					if (donhang.getOrderId() != dh.getOrderId()) {

						db.addDonHang(dh);
						for (SKU sku : dh.getSKUs()) {
							db.addSku(dh.getOrderId(), sku);
						}
					}
				}
				mAdapter = new DonHangAdapter(self, db.getAllDonHangDangGiao());
				actualListView.setAdapter(mAdapter);

				break;
			case 1:

				AlertDialog alert_exist = getAlertDialog(getParent(),
						getResources().getString(R.string.msg_donhang),
						getResources().getString(R.string.msg_not_exits));
				alert_exist.show();
				break;
			case 2:
				AlertDialog alert = getAlertDialog(getParent(), getResources()
						.getString(R.string.msg_donhang), getResources()
						.getString(R.string.msg_clocked));
				alert.show();

				break;
			case 3:
				AlertDialog alert_loc = getAlertDialog(getParent(),
						getResources().getString(R.string.msg_donhang),
						getResources().getString(R.string.msg_loc_error));
				alert_loc.show();
				break;
			case 1000:
				AlertDialog alert_invalid = getAlertDialog(getParent(),
						getResources().getString(R.string.msg_donhang),
						getResources().getString(R.string.msg_data_invalid));
				alert_invalid.show();
				break;
			case 1001:
				AlertDialog alert_system = getAlertDialog(getParent(),
						getResources().getString(R.string.msg_donhang),
						getResources().getString(R.string.msg_system_error));
				alert_system.show();

				break;

			case 1002:
				AlertDialog alert_token = getAlertDialog(getParent(),
						getResources().getString(R.string.msg_donhang),
						getResources().getString(R.string.msg_token_expire));
				alert_token.show();
				break;
			case 1003:
				AlertDialog alert_sign = getAlertDialog(getParent(),
						getResources().getString(R.string.msg_donhang),
						getResources().getString(R.string.msg_sign_error));
				alert_sign.show();
				break;
			default:
				break;
			}

			mAdapter.notifyDataSetChanged();

			// Call onRefreshComplete when the list has been refreshed.
			list_donhang.onRefreshComplete();

		}

	}

	OnItemClickListener onItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long arg3) {
			view.setSelected(true);

			DonHang dh = (DonHang) parent.getAdapter().getItem(position);

			Intent intent_donhang = new Intent(self,
					DonHangDetailActivity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable(DONHANG, dh);
			intent_donhang.putExtras(bundle);
			TabGroupActivity tabGroupActivity = (TabGroupActivity) getParent();
			tabGroupActivity.startChildActivity("DonHangDetailActivity",
					intent_donhang);
		}
	};

}
